package wht.jly.forum.config.security;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import wht.jly.forum.domain.User;
import wht.jly.forum.service.UserService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lanyangji
 * @date 2019/2/27 21:41
 */
@Component(value = "customUserDetailsService")
@Slf4j
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) {

        // 1. 根据用户名从数据库中查询用户信息
        User dbUser = userService.findByUsername(username);

        // 2. 如果查出为null,则抛出没有发现此用户异常
        if (dbUser == null) {
            throw new UsernameNotFoundException("没有此用户！");
        }

        // 3. 封装用户的角色码，角色码必须以 ‘ROLE_’ 开头
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> roleCodes = userService.findRoleCodeByUserId(dbUser.getId());
        roleCodes.stream().filter(StringUtils::isNotBlank).forEach(
                roleCode -> authorities.add(new SimpleGrantedAuthority("ROLE_" + roleCode))
        );

        // log
        log.info("用户 【{}】 尝试登录，角色码为 【{}】", username, roleCodes);

        return new org.springframework.security.core.userdetails.User(dbUser.getUsername(), dbUser.getPassword(), authorities);
    }
}
